'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import {
  Container,
  Box,
  Typography,
  Paper,
  CircularProgress,
  Alert,
  Button,
  Grid,
  Chip,
  IconButton,
  useTheme,
  alpha,
  Fade,
  Divider,
  List,
  ListItem,
  ListItemText,
  ListItemAvatar,
  Avatar,
  Card,
  CardContent,
} from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import WorkIcon from '@mui/icons-material/Work';
import VisibilityIcon from '@mui/icons-material/Visibility';
import EmailIcon from '@mui/icons-material/Email';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import AttachMoneyIcon from '@mui/icons-material/AttachMoney';
import PeopleIcon from '@mui/icons-material/People';
import MarkEmailReadIcon from '@mui/icons-material/MarkEmailRead';
import MarkEmailUnreadIcon from '@mui/icons-material/MarkEmailUnread';
import DescriptionIcon from '@mui/icons-material/Description';
import PersonIcon from '@mui/icons-material/Person';
import Navbar from '@/components/Navbar';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';

interface JobPost {
  id: number;
  title: string;
  company_name: string;
  location: string;
  salary_min?: number;
  salary_max?: number;
  salary_range?: string; // 添加salary_range字段
  job_type: string;
  is_active: boolean;
  views: number;
  applications: number;
  created_at: string;
  description?: string;
  requirements?: string;
}

interface ResumeApplication {
  id: number;
  user_name: string;
  user_avatar?: string;
  school: string;
  graduation_year: string;
  gender: string;
  phone: string;
  email: string;
  is_read: boolean;
  submitted_at: string;
  resume_file?: string;
}

interface JobPostStats {
  total_resumes: number;
  read_resumes: number;
  unread_resumes: number;
  applications: ResumeApplication[];
}

export default function JobPostDetailPage() {
  const router = useRouter();
  const params = useParams();
  const theme = useTheme();
  const [jobPost, setJobPost] = useState<JobPost | null>(null);
  const [stats, setStats] = useState<JobPostStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [fadeIn, setFadeIn] = useState(false);

  const jobPostId = params.id as string;

  const fetchJobPostDetail = async () => {
    setLoading(true);
    setError('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        router.push('/login');
        return;
      }

      const headers = {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      };

      // 获取招聘公告详情
      const [jobPostResponse, statsResponse] = await Promise.all([
        fetch(`/api/profile/job-posts/${jobPostId}`, { headers }),
        fetch(`/api/profile/job-posts/${jobPostId}/stats`, { headers })
      ]);

      if (jobPostResponse.status === 401 || statsResponse.status === 401) {
        // 清除无效的token和用户数据，然后跳转到登录页
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        localStorage.removeItem('userData');
        router.push('/login');
        return;
      }

      if (!jobPostResponse.ok || !statsResponse.ok) {
        throw new Error('获取招聘公告详情失败');
      }

      const jobPostData = await jobPostResponse.json();
      const statsData = await statsResponse.json();
      
      setJobPost(jobPostData);
      setStats(statsData);
      setFadeIn(true);
    } catch (error) {
      console.error('获取招聘公告详情失败:', error);
      setError((error as Error).message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // 立即检查登录状态
    const token = localStorage.getItem('token');
    if (!token) {
      console.log('用户未登录，跳转到登录页面');
      router.push('/login');
      return;
    }

    if (jobPostId) {
      fetchJobPostDetail();
    }
  }, [jobPostId, router]);

  const formatSalary = (min?: number, max?: number, salaryRange?: string) => {
    // 优先使用salary_range字段
    if (salaryRange) {
      return salaryRange;
    }
    // 兼容旧的格式
    if (!min && !max) return '面议';
    if (min && max) return `${min}k-${max}k`;
    if (min) return `${min}k+`;
    return '面议';
  };

  const getJobTypeLabel = (jobType: string) => {
    switch (jobType) {
      case 'full_time':
      case 'full-time':
        return '全职';
      case 'part_time':
      case 'part-time':
        return '兼职';
      case 'internship':
        return '实习';
      case 'contract':
        return '合同工';
      default:
        return jobType;
    }
  };

  const handleMarkAsRead = async (applicationId: number) => {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`/api/profile/job-posts/${jobPostId}/applications/${applicationId}/read`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      if (response.ok) {
        // 重新获取数据
        fetchJobPostDetail();
      }
    } catch (error) {
      console.error('标记已读失败:', error);
    }
  };

  if (loading) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
          <CircularProgress />
        </Box>
      </Container>
    );
  }

  if (error) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Alert severity="error" sx={{ mt: 4 }}>
          {error}
          <Button 
            onClick={() => window.location.reload()} 
            sx={{ ml: 2 }} 
            size="small"
          >
            重新加载
          </Button>
        </Alert>
      </Container>
    );
  }

  if (!jobPost || !stats) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Alert severity="error" sx={{ mt: 4 }}>
          招聘公告不存在
          <Button 
            onClick={() => fetchJobPostDetail()} 
            sx={{ ml: 2 }} 
            size="small"
          >
            重试
          </Button>
        </Alert>
      </Container>
    );
  }

  return (
    <Box sx={{ minHeight: '100vh', bgcolor: 'background.default' }}>
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Fade in={fadeIn} timeout={800}>
          <Box>
            {/* 页面头部 */}
            <Paper
              elevation={0}
              sx={{
                p: 3,
                mb: 4,
                borderRadius: '16px',
                backgroundColor: alpha('#fff', 0.9),
                backdropFilter: 'blur(10px)',
                boxShadow: '0 4px 30px rgba(0, 0, 0, 0.05)',
                border: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
              }}
            >
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
                <IconButton 
                  onClick={() => router.back()}
                  sx={{ mr: 2 }}
                >
                  <ArrowBackIcon />
                </IconButton>
                <WorkIcon sx={{ mr: 2, color: theme.palette.primary.main }} />
                <Typography variant="h4" sx={{ fontWeight: 600 }}>
                  {jobPost.title}
                </Typography>
                <Chip
                  label={jobPost.is_active ? '招聘中' : '已暂停'}
                  color={jobPost.is_active ? 'success' : 'default'}
                  size="small"
                  sx={{ ml: 2 }}
                />
              </Box>

              <Grid container spacing={3}>
                <Grid item xs={12} md={6}>
                  <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <LocationOnIcon color="action" fontSize="small" />
                      <Typography variant="body1">{jobPost.location}</Typography>
                    </Box>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <AttachMoneyIcon color="action" fontSize="small" />
                      <Typography variant="body1">{formatSalary(jobPost.salary_min, jobPost.salary_max, jobPost.salary_range)}</Typography>
                    </Box>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <WorkIcon color="action" fontSize="small" />
                      <Typography variant="body1">{getJobTypeLabel(jobPost.job_type)}</Typography>
                    </Box>
                  </Box>
                </Grid>
                <Grid item xs={12} md={6}>
                  <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <VisibilityIcon color="action" fontSize="small" />
                      <Typography variant="body1">浏览量: {jobPost.views}</Typography>
                    </Box>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <PeopleIcon color="action" fontSize="small" />
                      <Typography variant="body1">投递量: {jobPost.applications}</Typography>
                    </Box>
                    <Typography variant="body2" color="text.secondary">
                      发布时间: {format(new Date(jobPost.created_at), 'yyyy年MM月dd日', { locale: zhCN })}
                    </Typography>
                  </Box>
                </Grid>
              </Grid>
            </Paper>

            {/* 简历统计 */}
            <Grid container spacing={3} sx={{ mb: 4 }}>
              <Grid item xs={12} md={4}>
                <Card sx={{ textAlign: 'center', p: 2 }}>
                  <CardContent>
                    <Typography variant="h3" color="primary" sx={{ fontWeight: 600 }}>
                      {stats.total_resumes}
                    </Typography>
                    <Typography variant="h6" color="text.secondary">
                      总简历数
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid item xs={12} md={4}>
                <Card sx={{ textAlign: 'center', p: 2 }}>
                  <CardContent>
                    <Typography variant="h3" color="success.main" sx={{ fontWeight: 600 }}>
                      {stats.read_resumes}
                    </Typography>
                    <Typography variant="h6" color="text.secondary">
                      已读简历
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid item xs={12} md={4}>
                <Card sx={{ textAlign: 'center', p: 2 }}>
                  <CardContent>
                    <Typography variant="h3" color="warning.main" sx={{ fontWeight: 600 }}>
                      {stats.unread_resumes}
                    </Typography>
                    <Typography variant="h6" color="text.secondary">
                      未读简历
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
            </Grid>

            {/* 简历申请列表 */}
            <Paper
              elevation={0}
              sx={{
                borderRadius: '16px',
                overflow: 'hidden',
                border: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
              }}
            >
              <Box sx={{ p: 3, borderBottom: `1px solid ${alpha(theme.palette.divider, 0.1)}` }}>
                <Typography variant="h6" sx={{ fontWeight: 600 }}>
                  简历申请列表
                </Typography>
              </Box>

              {stats.applications.length > 0 ? (
                <List sx={{ p: 0 }}>
                  {stats.applications.map((application, index) => (
                    <React.Fragment key={application.id}>
                      <ListItem
                        sx={{
                          px: 3,
                          py: 2,
                          backgroundColor: application.is_read ? 'transparent' : alpha(theme.palette.primary.light, 0.05),
                        }}
                      >
                        <ListItemAvatar>
                          <Avatar
                            src={application.user_avatar}
                            sx={{
                              bgcolor: theme.palette.primary.main,
                              width: 50,
                              height: 50
                            }}
                          >
                            {application.user_avatar ? undefined : <PersonIcon />}
                          </Avatar>
                        </ListItemAvatar>
                        
                        <ListItemText
                          primary={
                            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                              <Typography
                                variant="subtitle1"
                                sx={{ fontWeight: application.is_read ? 400 : 600 }}
                              >
                                {application.user_name}
                              </Typography>
                              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                <Typography variant="caption" color="text.secondary">
                                  {format(new Date(application.submitted_at), 'MM/dd HH:mm', { locale: zhCN })}
                                </Typography>
                                {!application.is_read && (
                                  <Chip
                                    size="small"
                                    label="新"
                                    color="primary"
                                    sx={{ height: 20, fontSize: '0.7rem' }}
                                  />
                                )}
                                <IconButton
                                  size="small"
                                  color={application.is_read ? 'default' : 'primary'}
                                  onClick={() => handleMarkAsRead(application.id)}
                                  disabled={application.is_read}
                                >
                                  {application.is_read ? <MarkEmailReadIcon fontSize="small" /> : <MarkEmailUnreadIcon fontSize="small" />}
                                </IconButton>
                              </Box>
                            </Box>
                          }
                          secondary={
                            <Box sx={{ mt: 1 }}>
                              <Typography variant="body2" color="text.secondary">
                                {application.school} · {application.graduation_year}届 · {application.gender}
                              </Typography>
                              <Typography variant="body2" color="text.secondary">
                                {application.email} · {application.phone}
                              </Typography>
                              {application.resume_file && (
                                <Box sx={{ mt: 1 }}>
                                  <Chip
                                    icon={<DescriptionIcon fontSize="small" />}
                                    label="查看简历"
                                    size="small"
                                    variant="outlined"
                                    clickable
                                  />
                                </Box>
                              )}
                            </Box>
                          }
                        />
                      </ListItem>
                      {index < stats.applications.length - 1 && <Divider variant="inset" component="li" />}
                    </React.Fragment>
                  ))}
                </List>
              ) : (
                <Box sx={{ p: 6, textAlign: 'center' }}>
                  <EmailIcon sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
                  <Typography variant="h6" color="text.secondary" sx={{ mb: 1 }}>
                    暂无简历投递
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    还没有求职者投递简历到这个职位
                  </Typography>
                </Box>
              )}
            </Paper>
          </Box>
        </Fade>
      </Container>
    </Box>
  );
} 